package com.atguigu.tingshu.user.strategy.factory;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 策略工厂：管理所有策略实现类对象；对外提供根据商品类型返回策略实现对象方法
 *
 * @author: atguigu
 * @create: 2025-03-25 09:14
 */
@Slf4j
@Component
public class StrategyFactory {


    /**
     * 自动注入方式为Map注入
     * Map中key是Bean对象ID，自动从IOC容器中获取PaidRecordStrategy类型Bean，value是策略实现类Bean对象
     */
    @Autowired
    private Map<String, PaidRecordStrategy> strategyMap;

    /**
     * 获取策略实现类对象注入到List
     */
    @Autowired
    private List<PaidRecordStrategy> listStrategy;


    /**
     * 根据商品类型返回策略实现对象
     * @param type
     * @return
     */
    public PaidRecordStrategy getStrategy(String type) {
        //根据商品类型返回对应的策略实现类对象
        if (!strategyMap.containsKey(type)) {
            log.error("[用户服务-策略工厂]未找到适配策略实现类:{}", type);
            throw new GuiguException(500, "未找到适配策略实现类");
        }
        PaidRecordStrategy strategy = strategyMap.get(type);
        log.info("[用户服务-策略工厂]根据商品类型返回对应的策略实现类对象：{}", strategy);
        return strategy;
    }
}
